package com.seeingtv.service.impl;

import com.seeingtv.common.utils.StringUtils;
import com.seeingtv.model.Menu;
import com.seeingtv.mapper.MenuMapper;
import com.seeingtv.service.MenuService;
import com.seeingtv.common.utils.TreeUtils;
import org.apache.shiro.cache.CacheManager;
import org.apache.shiro.cache.Cache;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * @author hubert
 * @date 2018/8/2
 * @description MenuServiceImpl
 *
 */
@Service
public class MenuServiceImpl implements MenuService {

	@Autowired
    private CacheManager cacheManager;

	@Autowired
	private MenuMapper menuMapper;

	private Cache<String, List<Menu>> menusCache;

	@PostConstruct
    public void init() {
		menusCache = cacheManager.getCache("loginRecordCache");
    }

	/**
	 * 根据用户ID查询菜单
	 *
	 * @param userId 用户ID
	 * @return 菜单列表
	 */
	@Override
	public List<Menu> selectMenusByUserId(Long userId) {
		List<Menu> menus = menuMapper.selectMenusByUserId(userId);
		return TreeUtils.getChildPerms(menus, 0);
	}

	@Override
	public String selectMenuIdsByRoleId(Long roleId) {
		return menuMapper.selectMenuIdsByRoleId(roleId);
	}

	/**
	 * 缓存菜单
	 * Cacheable(value="loginRecordCache") 未通spring注入，注解不生效
	 * 为避免缓存冲突，应根据用户进行缓存，不同用户缓存的菜单信息不一样
	 */
	@Override
	public List<Menu> selectMenusById(String[] menuId) {
		List<Menu> menus = menusCache.get("menus");
		if (menus == null) {
			menus = TreeUtils.getChildPerms(menuMapper.selectMenusByUId(menuId),0);
			//加入缓存
			menusCache.put("menus",menus);
		}
		return menus;
	}

	/**
	 * 根据用户ID查询权限
	 *
	 * @param userId 用户ID
	 * @return 权限列表
	 */
	@Override
	public Set<String> selectPermsByUserId(Long userId) {
		List<String> perms = menuMapper.selectPermsByCode("t_cp");
		Set<String> permsSet = new HashSet<>();
		for (String perm : perms) {
			if (StringUtils.isNotEmpty(perm)) {
				permsSet.addAll(Arrays.asList(perm.trim().split(",")));
			}
		}
		return permsSet;
	}
}
